<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>环境监测 - 智慧农业管理系统</title>
    <!-- 引入ECharts图表库 -->
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.2/dist/echarts.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: "PingFang SC", "Microsoft YaHei", sans-serif;
        }

        body {
            min-height: 100vh;
            background-color: #f8faf6;
            color: #334155;
        }

        /* 顶部导航栏 */
        .header {
            background: linear-gradient(135deg, #4caf50 0%, #81c784 100%);
            color: white;
            padding: 20px 40px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
            position: relative;
            z-index: 10;
        }

        .logo {
            display: flex;
            align-items: center;
        }

        .logo h1 {
            font-size: 24px;
            font-weight: 700;
        }

        .user-info {
            display: flex;
            align-items: center;
        }

        .user-info span {
            margin-right: 15px;
            font-weight: 500;
        }

        .user-info .avatar {
            width: 36px;
            height: 36px;
            border-radius: 50%;
            background-color: #f1f8e9;
            display: flex;
            justify-content: center;
            align-items: center;
            color: #4caf50;
            font-weight: 600;
            cursor: pointer;
            position: relative;
        }

        .dropdown-menu {
            position: absolute;
            top: 100%;
            right: 0;
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
            padding: 8px 0;
            min-width: 160px;
            z-index: 100;
            display: none;
            margin-top: 10px;
        }

        .dropdown-menu.show {
            display: block;
        }

        .dropdown-item {
            display: block;
            padding: 10px 20px;
            color: #333;
            text-decoration: none;
            transition: background-color 0.2s;
        }

        .dropdown-item:hover {
            background-color: #f1f8e9;
            color: #2e7d32;
        }

        .dropdown-divider {
            height: 1px;
            background-color: #e0e0e0;
            margin: 8px 0;
        }

        /* 主内容区域 */
        .main-content {
            display: flex;
            min-height: calc(100vh - 80px);
        }

        /* 左侧导航 */
        .sidebar {
            width: 220px;
            background: #e8f5e9;
            padding: 20px 0;
            box-shadow: 2px 0 10px rgba(0, 0, 0, 0.05);
            position: relative;
            z-index: 5;
        }

        .nav-group {
            margin-bottom: 30px;
        }

        .nav-title {
            color: #2e7d32;
            font-size: 16px;
            font-weight: 600;
            padding: 10px 25px;
            margin-bottom: 10px;
        }

        .nav-item {
            display: block;
            padding: 12px 25px;
            color: #334155;
            text-decoration: none;
            transition: all 0.2s ease;
        }

        .nav-item:hover {
            background-color: #c8e6c9;
            color: #2e7d32;
        }

        .nav-item.active {
            background-color: #a5d6a7;
            color: #2e7d32;
            font-weight: 500;
            border-left: 4px solid #4caf50;
        }

        /* 内容区域 */
        .content {
            flex: 1;
            padding: 30px;
        }

        .page-title {
            font-size: 24px;
            font-weight: 600;
            color: #2e7d32;
            margin-bottom: 20px;
        }

        .card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
            padding: 25px;
            margin-bottom: 25px;
        }

        .card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }

        .card-title {
            font-size: 18px;
            font-weight: 600;
            color: #334155;
        }

        .btn {
            padding: 8px 16px;
            border: none;
            border-radius: 6px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s ease;
        }

        .btn-primary {
            background-color: #4caf50;
            color: white;
        }

        .btn-primary:hover {
            background-color: #388e3c;
        }

        /* 环境监测卡片 */
        .monitor-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
            gap: 20px;
        }

        .monitor-card {
            background: #f9f9f9;
            border-radius: 8px;
            padding: 20px;
            text-align: center;
            transition: all 0.3s ease;
        }

        .monitor-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 15px rgba(0, 0, 0, 0.1);
        }

        .monitor-card h3 {
            font-size: 16px;
            color: #555;
            margin-bottom: 15px;
        }

        .monitor-value {
            font-size: 32px;
            font-weight: 700;
            color: #2e7d32;
            margin-bottom: 10px;
        }

        .monitor-status {
            display: inline-block;
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 500;
        }

        .status-normal {
            background-color: #e8f5e9;
            color: #2e7d32;
        }

        .status-warning {
            background-color: #fff3e0;
            color: #ef6c00;
        }

        .status-danger {
            background-color: #ffebee;
            color: #c62828;
        }

        /* 图表容器 */
        .chart-container {
            height: 400px;
            margin-top: 20px;
        }

        .location-info {
            display: flex;
            justify-content: space-between;
            margin-bottom: 20px;
            color: #666;
            font-size: 14px;
        }
    </style>
</head>
<body>
<!-- 顶部导航 -->
<div class="header">
    <div class="logo">
        <div class="logo-icon">🌱</div>
        <h1>智慧农业管理系统</h1>
    </div>
    <div class="user-info">
        <span>管理员</span>
        <div class="avatar" id="userAvatar">管</div>
        <div class="dropdown-menu" id="userDropdown">
            <a href="#" class="dropdown-item" onclick="showProfile()">个人设置</a>
            <div class="dropdown-divider"></div>
            <a href="#" class="dropdown-item" onclick="logout()">退出登录</a>
        </div>
    </div>
</div>

<!-- 主内容区 -->
<div class="main-content">
    <!-- 左侧导航 -->
    <div class="sidebar">
        <div class="nav-group">
            <div class="nav-title">系统导航</div>
            <a href="main.jsp" class="nav-item">系统首页</a>
            <a href="deviceManagement.jsp" class="nav-item">设备管理</a>
        </div>

        <div class="nav-group">
            <div class="nav-title">农业管理</div>
            <a href="environmentMonitor.jsp" class="nav-item active">环境监测</a>
            <a href="pestControl.jsp" class="nav-item">病虫害防治</a>
            <a href="irrigationControl.jsp" class="nav-item">灌溉施肥</a>
        </div>

        <div class="nav-group">
            <div class="nav-title">系统设置</div>
            <a href="userServlet?actionType=list" class="nav-item">用户管理</a>
            <a href="system_config.jsp" class="nav-item">系统配置</a>
            <a href="tech.jsp" class="nav-item">技术支持</a>
            <a href="we.jsp" class="nav-item">关于我们</a>
        </div>
    </div>

    <!-- 内容区域 -->
    <div class="content">
        <h1 class="page-title">环境监测</h1>

        <div class="card">
            <div class="card-header">
                <h2 class="card-title">实时环境数据</h2>
                <button class="btn btn-primary" onclick="refreshData()">刷新数据</button>
            </div>

            <div class="location-info">
                <div>监测区域：XX示范基地 - 温室大棚A区</div>
                <div id="updateTime">最后更新：2025-07-12 10:30:00</div>
            </div>

            <div class="monitor-grid">
                <div class="monitor-card">
                    <h3>土壤湿度</h3>
                    <div class="monitor-value" id="soilMoisture">65%</div>
                    <span class="monitor-status status-normal">正常</span>
                </div>
                <div class="monitor-card">
                    <h3>空气温度</h3>
                    <div class="monitor-value" id="airTemperature">26℃</div>
                    <span class="monitor-status status-normal">正常</span>
                </div>
                <div class="monitor-card">
                    <h3>空气湿度</h3>
                    <div class="monitor-value" id="airHumidity">70%</div>
                    <span class="monitor-status status-normal">正常</span>
                </div>
                <div class="monitor-card">
                    <h3>光照强度</h3>
                    <div class="monitor-value" id="lightIntensity">8000 lux</div>
                    <span class="monitor-status status-normal">正常</span>
                </div>
                <div class="monitor-card">
                    <h3>二氧化碳浓度</h3>
                    <div class="monitor-value" id="co2Level">450 ppm</div>
                    <span class="monitor-status status-warning">偏高</span>
                </div>
                <div class="monitor-card">
                    <h3>土壤pH值</h3>
                    <div class="monitor-value" id="soilPH">6.8</div>
                    <span class="monitor-status status-normal">正常</span>
                </div>
            </div>
        </div>

        <div class="card">
            <div class="card-header">
                <h2 class="card-title">历史数据趋势</h2>
                <div>
                    <button class="btn btn-primary" id="btn24Hours" onclick="switchChartData('24hours')">24小时</button>
                    <button class="btn" id="btn7Days" onclick="switchChartData('7days')">7天</button>
                </div>
            </div>
            <div class="chart-container" id="chartContainer">
                <!-- 图表将在这里渲染 -->
            </div>
        </div>
    </div>
</div>

<script>
    // 用户下拉菜单功能
    document.addEventListener('DOMContentLoaded', function() {
        const userAvatar = document.getElementById('userAvatar');
        const userDropdown = document.getElementById('userDropdown');

        // 点击头像显示/隐藏下拉菜单
        userAvatar.addEventListener('click', function(e) {
            e.stopPropagation();
            userDropdown.classList.toggle('show');
        });

        // 点击页面其他地方隐藏下拉菜单
        document.addEventListener('click', function() {
            userDropdown.classList.remove('show');
        });

        // 阻止下拉菜单内部点击事件冒泡
        userDropdown.addEventListener('click', function(e) {
            e.stopPropagation();
        });

        // 设置每天自动更新数据（先加载数据）
        setupDailyUpdate();

        // 初始化图表（在数据加载后）
        initChart();
    });

    // 设置每天自动更新数据
    function setupDailyUpdate() {
        // 检查是否需要更新数据（每天更新一次）
        const lastUpdate = localStorage.getItem('environmentDataLastUpdate');
        const now = new Date();
        const today = now.toDateString();

        // 如果没有上次更新记录，或者上次更新不是今天，则更新数据
        if (!lastUpdate || lastUpdate !== today) {
            refreshData();
            localStorage.setItem('environmentDataLastUpdate', today);
        } else {
            // 如果今天已经更新过，使用存储的数据
            loadStoredData();
        }

        // 设置定时器，在每天0点0分更新数据
        const tomorrow = new Date(now);
        tomorrow.setDate(tomorrow.getDate() + 1);
        tomorrow.setHours(0, 0, 0, 0);
        const timeUntilMidnight = tomorrow.getTime() - now.getTime();

        setTimeout(function() {
            refreshData();
            localStorage.setItem('environmentDataLastUpdate', new Date().toDateString());
            // 重新设置下一天的更新
            setupDailyUpdate();
        }, timeUntilMidnight);
    }

    // 加载存储的数据
    function loadStoredData() {
        const storedData = localStorage.getItem('environmentTodayData');
        if (storedData) {
            const data = JSON.parse(storedData);
            // 更新实时环境数据
            document.getElementById('soilMoisture').textContent = data.soilMoisture + '%';
            document.getElementById('airTemperature').textContent = data.airTemperature + '℃';
            document.getElementById('airHumidity').textContent = data.airHumidity + '%';
            document.getElementById('lightIntensity').textContent = data.lightIntensity + ' lux';
            document.getElementById('co2Level').textContent = data.co2Level + ' ppm';
            document.getElementById('soilPH').textContent = data.soilPH.toFixed(1);

            // 存储基础数据供图表使用
            window.environmentBaseData = {
                temperature: data.airTemperature,
                humidity: data.airHumidity,
                light: data.lightIntensity,
                co2: data.co2Level,
                soilMoisture: data.soilMoisture,
                soilPH: data.soilPH
            };
        }
    }

    // 显示个人设置
    function showProfile() {
        window.location.href = 'profile.jsp';
    }

    // 退出登录
    function logout() {
        if (confirm('确定要退出登录吗？')) {
            fetch('logout', {
                method: 'POST'
            })
            .then(response => {
                if (response.ok) {
                    window.location.href = 'login.jsp';
                } else {
                    alert('退出登录失败，请稍后再试');
                }
            })
            .catch(error => {
                console.error('退出登录失败:', error);
                alert('退出登录失败，请稍后再试');
            });
        }
    }

    // 刷新数据
    function refreshData() {
        // 模拟刷新数据
        document.getElementById('updateTime').textContent = '最后更新：' + new Date().toLocaleString();

        // 使用固定的预设值
        const today = new Date().getDay(); // 获取今天是星期几(0-6, 0代表周日)

        // 根据星期几设置不同的固定值，模拟每天的环境变化
        const presetValues = [
            {soilMoisture: 65, airTemperature: 24, airHumidity: 68, lightIntensity: 7500, co2Level: 420, soilPH: 6.8}, // 周日
            {soilMoisture: 62, airTemperature: 23, airHumidity: 70, lightIntensity: 7200, co2Level: 430, soilPH: 6.7}, // 周一
            {soilMoisture: 68, airTemperature: 25, airHumidity: 65, lightIntensity: 8000, co2Level: 410, soilPH: 6.9}, // 周二
            {soilMoisture: 64, airTemperature: 26, airHumidity: 63, lightIntensity: 8200, co2Level: 440, soilPH: 6.8}, // 周三
            {soilMoisture: 66, airTemperature: 25, airHumidity: 66, lightIntensity: 7800, co2Level: 425, soilPH: 6.7}, // 周四
            {soilMoisture: 63, airTemperature: 24, airHumidity: 69, lightIntensity: 7600, co2Level: 415, soilPH: 6.9}, // 周五
            {soilMoisture: 67, airTemperature: 23, airHumidity: 67, lightIntensity: 7400, co2Level: 435, soilPH: 6.8}  // 周六
        ];

        const todayValues = presetValues[today];

        // 更新实时环境数据
        document.getElementById('soilMoisture').textContent = todayValues.soilMoisture + '%';
        document.getElementById('airTemperature').textContent = todayValues.airTemperature + '℃';
        document.getElementById('airHumidity').textContent = todayValues.airHumidity + '%';
        document.getElementById('lightIntensity').textContent = todayValues.lightIntensity + ' lux';
        document.getElementById('co2Level').textContent = todayValues.co2Level + ' ppm';
        document.getElementById('soilPH').textContent = todayValues.soilPH.toFixed(1);

        // 存储基础数据供图表使用
        window.environmentBaseData = {
            temperature: todayValues.airTemperature,
            humidity: todayValues.airHumidity,
            light: todayValues.lightIntensity,
            co2: todayValues.co2Level,
            soilMoisture: todayValues.soilMoisture,
            soilPH: todayValues.soilPH
        };

        // 更新图表
        updateChart();
    }

    // 切换图表数据
    function switchChartData(type) {
        // 更新按钮状态
        document.getElementById('btn24Hours').classList.remove('btn-primary');
        document.getElementById('btn7Days').classList.remove('btn-primary');

        if (type === '24hours') {
            document.getElementById('btn24Hours').classList.add('btn-primary');
        } else {
            document.getElementById('btn7Days').classList.add('btn-primary');
        }

        // 更新图表
        updateChart(type);
    }

    // 初始化图表
    function initChart() {
        const chartContainer = document.getElementById('chartContainer');
        chartContainer.innerHTML = '<div style="display: flex; justify-content: center; align-items: center; height: 100%; color: #666;">图表加载中...</div>';

        // 初始化ECharts实例
        setTimeout(() => {
            // 创建ECharts实例
            window.environmentChart = echarts.init(chartContainer);
            updateChart('24hours');
        }, 1000);
    }

    // 更新图表
    function updateChart(type) {
        if (!window.environmentChart) {
            // 如果图表实例不存在，创建它并直接更新
            const chartContainer = document.getElementById('chartContainer');
            window.environmentChart = echarts.init(chartContainer);
        }

        // 生成模拟数据
        const now = new Date();
        let timeData = [];
        let temperatureData = [];
        let humidityData = [];
        let lightData = [];
        let co2Data = [];

        // 获取基础数据
        const baseData = window.environmentBaseData || {
            temperature: 25,
            humidity: 65,
            light: 6500,
            co2: 450,
            soilMoisture: 65,
            soilPH: 6.8
        };

        if (type === '24hours') {
            // 生成24小时数据，每小时一个点
            for (let i = 23; i >= 0; i--) {
                const time = new Date(now.getTime() - i * 3600 * 1000);
                timeData.push(time.getHours() + ':00');

                // 模拟数据，基于时间变化
                const hourFactor = 1 - Math.abs(time.getHours() - 14) / 14; // 中午温度最高
                // 基于基础数据生成温度数据
                temperatureData.push(baseData.temperature * (0.9 + 0.2 * hourFactor));
                // 基于基础数据生成湿度数据
                humidityData.push(baseData.humidity);
                const lightFactor = time.getHours() >= 6 && time.getHours() <= 18 ?
                    (1 - Math.abs(time.getHours() - 12) / 6) : 0; // 白天有光照
                lightData.push(baseData.light * lightFactor);
                // 基于基础数据生成CO2数据
                co2Data.push(baseData.co2);
            }
        } else {
            // 生成7天数据，每天一个点
            const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
            for (let i = 6; i >= 0; i--) {
                const time = new Date(now.getTime() - i * 24 * 3600 * 1000);
                timeData.push(days[time.getDay()]);

                // 使用预设的每日固定值
                const dayOfWeek = time.getDay();
                const dayPresetValues = [
                    {soilMoisture: 65, airTemperature: 24, airHumidity: 68, lightIntensity: 7500, co2Level: 420, soilPH: 6.8}, // 周日
                    {soilMoisture: 62, airTemperature: 23, airHumidity: 70, lightIntensity: 7200, co2Level: 430, soilPH: 6.7}, // 周一
                    {soilMoisture: 68, airTemperature: 25, airHumidity: 65, lightIntensity: 8000, co2Level: 410, soilPH: 6.9}, // 周二
                    {soilMoisture: 64, airTemperature: 26, airHumidity: 63, lightIntensity: 8200, co2Level: 440, soilPH: 6.8}, // 周三
                    {soilMoisture: 66, airTemperature: 25, airHumidity: 66, lightIntensity: 7800, co2Level: 425, soilPH: 6.7}, // 周四
                    {soilMoisture: 63, airTemperature: 24, airHumidity: 69, lightIntensity: 7600, co2Level: 415, soilPH: 6.9}, // 周五
                    {soilMoisture: 67, airTemperature: 23, airHumidity: 67, lightIntensity: 7400, co2Level: 435, soilPH: 6.8}  // 周六
                ];
                const dayValues = dayPresetValues[dayOfWeek];

                temperatureData.push(dayValues.airTemperature);
                humidityData.push(dayValues.airHumidity);
                lightData.push(dayValues.lightIntensity);
                co2Data.push(dayValues.co2Level);
            }
        }

        // 图表配置
        const option = {
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'cross',
                    label: {
                        backgroundColor: '#6a7985'
                    }
                }
            },
            legend: {
                data: ['温度', '湿度', '光照强度', '二氧化碳浓度'],
                top: 0
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                data: timeData
            },
            yAxis: [
                {
                    type: 'value',
                    name: '温度/湿度',
                    position: 'left',
                    axisLine: {
                        lineStyle: {
                            color: '#5470c6'
                        }
                    },
                    axisLabel: {
                        formatter: '{value} °C/%'
                    }
                },
                {
                    type: 'value',
                    name: '光照强度',
                    position: 'right',
                    axisLine: {
                        lineStyle: {
                            color: '#91cc75'
                        }
                    },
                    axisLabel: {
                        formatter: '{value} lux'
                    }
                },
                {
                    type: 'value',
                    name: '二氧化碳浓度',
                    position: 'right',
                    offset: 80,
                    axisLine: {
                        lineStyle: {
                            color: '#32cd32'
                        }
                    },
                    axisLabel: {
                        formatter: '{value} ppm'
                    }
                }
            ],
            series: [
                {
                    name: '温度',
                    type: 'line',
                    smooth: true,
                    data: temperatureData,
                    itemStyle: {
                        color: '#ff7f50'
                    }
                },
                {
                    name: '湿度',
                    type: 'line',
                    smooth: true,
                    data: humidityData,
                    itemStyle: {
                        color: '#4169e1'
                    }
                },
                {
                    name: '光照强度',
                    type: 'line',
                    smooth: true,
                    yAxisIndex: 1,
                    data: lightData,
                    itemStyle: {
                        color: '#ffd700'
                    }
                },
                {
                    name: '二氧化碳浓度',
                    type: 'line',
                    smooth: true,
                    yAxisIndex: 2,
                    data: co2Data,
                    itemStyle: {
                        color: '#32cd32'
                    }
                }
            ]
        };

        // 应用配置并渲染图表
        window.environmentChart.setOption(option);
    }
</script>
</body>
</html>